/**
 * Functions related to faster building entities from templates
 */

import { addComponent, addEntity, type IWorld } from '$lib/ecs';
import { Glyph } from './components';

export const withCustomGlyph = (et, glyph) => {
  return [...et, [Glyph, { glyph }]];
};

export const withoutComponent = (et, component) => {
  return et.filter(([c, v]) => c !== component);
};

export const mergeTemplates = (et, more) => {
  // this sounds very ineffective, but we are not supposed to do it more than once per template
  return more.reduce(
    (t, [comp, vs]) => {
      const ix = t.findIndex(([c]) => c === comp);
      if (ix !== -1) {
        return [...t.slice(0, ix), ...t.slice(ix+1), [comp, {...t[ix][1], ...vs}]];
      } else {
        return [...t, [comp, vs]];
      }
    },
    et
  );
};

export const fromTemplate = (world: IWorld, t, e?) => {
  if (e === undefined)
    e = addEntity(world);
  for (let [component, init] of t) {
    addComponent(world, component, e, init);
  }
  return e;
};
